package com.hibiscusking.basic.interptor;

import com.hibiscusking.basic.anno.PreAuthorize;
import com.hibiscusking.basic.jwt.JwtUtils;
import com.hibiscusking.basic.jwt.Payload;
import com.hibiscusking.basic.jwt.RsaUtils;
import com.hibiscusking.basic.jwt.UserInfo;
import com.hibiscusking.system.mapper.PermissionMapper;
import com.hibiscusking.user.domain.Logininfo;
import com.hibiscusking.user.domain.User;
import jdk.nashorn.internal.parser.Token;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String key = request.getHeader("token");
        if (StringUtils.isNotBlank(key)){
//            Logininfo logininfo = (Logininfo) redisTemplate.opsForValue().get(key);
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("jwt/pethome_auth_rsa.pub").getFile());
            Payload<UserInfo> userInfoPayload = JwtUtils.getInfoFromToken(key, publicKey, UserInfo.class);
            UserInfo userInfo = userInfoPayload.getUserInfo();
            if (null != userInfo.getLogininfo()) {
                if (userInfo.getLogininfo().getType() == 0) {
                    // 获取本次请求的方法对象
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    // 获取当前方法上的注解
                    PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                    // 判断是否有这个注解，没有的话说明是都可以使用的方法，没有限制
                    if (preAuthorize != null) {
//                        List<String>  jurisdiction= permissionMapper.findByLoginId(userInfo.getLogininfo().getId());
                        List<String> jurisdiction = userInfo.getPermission();
                        String sn = preAuthorize.sn();
                        if (!jurisdiction.contains(sn)){
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
                            writer.flush();
                            writer.close();
                            return false;
                        }
                    }
                }
//                redisTemplate.expire(key,30, TimeUnit.MINUTES);
                return true;
            }
        }
        // 3.1.设置编码字符集
        response.setCharacterEncoding("UTF-8");
        // 3.2.设置响应参数类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        // 3.3.获取到打印流,并设置响应数据
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
        // 3.4.刷新、关流
        writer.flush();
        writer.close();
        return false;
//        String key = request.getHeader("token");
//        if (StringUtils.isNotBlank(key)){
//            Logininfo logininfo = (Logininfo) redisTemplate.opsForValue().get(key);
//                if (null != logininfo) {
//                    if (logininfo.getType() == 0) {
//                        // 获取本次请求的方法对象
//                        HandlerMethod handlerMethod = (HandlerMethod) handler;
//                        // 获取当前方法上的注解
//                        PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
//                        // 判断是否有这个注解，没有的话说明是都可以使用的方法，没有限制
//                        if (preAuthorize != null) {
//                            List<String>  jurisdiction= permissionMapper.findByLoginId(logininfo.getId());
//                            String sn = preAuthorize.sn();
//                            if (!jurisdiction.contains(sn)){
//                                PrintWriter writer = response.getWriter();
//                                writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
//                                writer.flush();
//                                writer.close();
//                                return false;
//                            }
//                        }
//                    }
//
//                    redisTemplate.expire(key,30, TimeUnit.MINUTES);
//                    return true;
//                }
//        }
//        // 3.1.设置编码字符集
//        response.setCharacterEncoding("UTF-8");
//        // 3.2.设置响应参数类型为JSON
//        response.setContentType("application/json;charset=UTF-8");
//        // 3.3.获取到打印流,并设置响应数据
//        PrintWriter writer = response.getWriter();
//        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
//        // 3.4.刷新、关流
//        writer.flush();
//        writer.close();
//        return false;
    }
}
